import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.*;
import java.text.*;

class regleDateService{
	int num;
	String type;
	Date dateDebut;
	Date dateFin;
	int periode;
	regleDateService(int num , String type, Date dateDebut, Date dateFin , int periode){
		this.num = num;
		this.type = type ;
		this.dateDebut = dateDebut;
		this.dateFin = dateFin;
		this.periode = periode;
	}
    public String toString(){
        return "("+this.num+" " + this.type+" " +this.dateDebut+" " +this.dateFin+" " +this.periode+")" ;
    }
	
}

class horaireService{
	//crenau_horaire_service
    //
	int num;

	Date dateDebut;
    Date dateFin;
	int duree;
	horaireService(int num , Date dateDebut, int duree){
		this.num = num;
		this.dateDebut = dateDebut;
		this.duree = duree;
	}
      public String toString(){
          return "("+this.num+" " +this.dateDebut+" "+" " + this.duree+")";
      }
	
}



public class createDateFromServiceRule {
    final static DateFormat formatter = new SimpleDateFormat("yyyy-M-d",Locale.FRANCE);
    final static DateFormat formatterTime = new SimpleDateFormat("HH:mm",Locale.FRANCE);
    final static DateFormat formatterTimeDate = new SimpleDateFormat("yyyy-M-d HH:mm:ss",Locale.FRANCE);

  
    
    /*
     A partir des regles li& au date périodique sur les semaines calcule les dates qui corresponde
     Ensuite itere avec les heures pour calculer date de debut et date de fin de chaque service
     */
    public static void calcDateSurJourSemaine(int serviceNum, regleDateService info,ArrayList listeHoraire)  {
        // différence des jours numérote entre java et sqlite java commence à 1 pour Day_OF_WEEK sqlite à 0
		try{
		Class.forName("org.sqlite.JDBC");
		Connection conn = DriverManager.getConnection("jdbc:sqlite:planning.db");
		Statement stat = conn.createStatement();
		
		Calendar calCourante = Calendar.getInstance();
        Calendar calFin = Calendar.getInstance();
        
        calCourante.setTime( info.dateDebut );
        calFin.setTime( info.dateFin );

        while (calCourante.before(calFin)) {
            if ((calCourante.get( Calendar.DAY_OF_WEEK)-1) ==info.periode) {
                //System.out.println(formatterTimeDate.format (calCourante.getTime()));
                Iterator i = listeHoraire.iterator();
                
                while(i.hasNext()){
                    Calendar dateDebutServiceCourant = (Calendar)calCourante.clone();
                    Calendar dateFinServiceCourant = (Calendar)calCourante.clone();
                    
                    Calendar heureDepart = Calendar.getInstance();
                    
                    horaireService horaire = (horaireService) i.next();
					String requete="Insert into date_service_reel values ("+info.num+" , "+ horaire.num +",";

                    heureDepart.setTime(horaire.dateDebut);
                  //   System.out.println(heureDepart.get(Calendar.HOUR_OF_DAY));
                    dateDebutServiceCourant.set(Calendar.HOUR_OF_DAY,heureDepart.get(Calendar.HOUR_OF_DAY));
                     dateFinServiceCourant.set(Calendar.HOUR_OF_DAY,heureDepart.get(Calendar.HOUR_OF_DAY));
                    dateFinServiceCourant.add( Calendar.MINUTE, horaire.duree);
                    
                    requete = requete +"\""+ formatterTimeDate.format(dateDebutServiceCourant.getTime())+ "\",";
					requete = requete +"\""+ formatterTimeDate.format(dateFinServiceCourant.getTime())+ "\"";

//                    System.out.println(formatterTimeDate.format(dateDebutServiceCourant.getTime()) +"  *** " + formatterTimeDate.format(dateFinServiceCourant.getTime()));
                    
					
					requete=requete+");";
					//System.out.println(requete);
					stat.executeUpdate(requete);
                    
                }
                
                
            }
            //INC date
            calCourante.add( Calendar.DATE, 1 );

        }
		}catch (Exception E) {
			System.out.println(E);
		}
       
    }

	public  static void main(String args[]){
		
		LinkedList pile = new LinkedList();
		System.out.println(" DEM add entree service vis à vis regle de calcul et horaire");
		try{
			Class.forName("org.sqlite.JDBC");
			Connection conn = DriverManager.getConnection("jdbc:sqlite:planning.db");
			Statement stat = conn.createStatement();
			ResultSet rs = stat.executeQuery("select * from service;");
			while (rs.next()) {
			/*	System.out.println("num  = " + rs.getString("num"));
				System.out.println(" name = " + rs.getString("name"));
			*/	
				pile.push(new Integer(	rs.getString("num")));
				
			}
			//final DateFormat formatter = new SimpleDateFormat("yyyy-M-d hh:mm:ss");
			

			// The calendar instance which adds a locale to the date
			final Calendar cal = Calendar.getInstance();
//			System.out.println(pile);
			while (pile.size()>0){
//				stat = conn.createStatement();
				String serviceNum= pile.pop().toString();
				ArrayList  listeRegleDate= new ArrayList();
				ArrayList  listeHoraire= new ArrayList();

				String req = "select * from regle_date_service where num_service="+serviceNum+";";
				rs = stat.executeQuery(req);
				//System.out.println(rs+"\n"+req);
				while (rs.next()) {
					/*System.out.println("num  = " + rs.getString("num") +
									   " " + rs.getString("type") +
									" " + rs.getString("date_deb") +
									     " " + rs.getString("date_fin")+
									" " + rs.getString("periode"));*/
					regleDateService crt = new regleDateService(Integer.parseInt(rs.getString("num")),
																rs.getString("type"),
																 createDateFromServiceRule.formatter.parse(rs.getString("date_deb")),
																 createDateFromServiceRule.formatter.parse(rs.getString("date_fin")),
																Integer.parseInt(rs.getString("periode")));
					listeRegleDate.add(crt);
				}
				req = "select * from crenau_horaire_service where num_service="+serviceNum+";";
				rs = stat.executeQuery(req);
				while (rs.next()) {
                    //(num  INTEGER PRIMARY KEY ,num_service INTEGER, heure_debut TEXT , duree INTEGER);
                    horaireService crt = new horaireService(Integer.parseInt(rs.getString("num")),
                                                           createDateFromServiceRule.formatterTime.parse(rs.getString("heure_debut")),
                                                            Integer.parseInt(rs.getString("duree")));
                    
                    listeHoraire.add(crt);
					
				}

				
				//System.out.println("horaire \n"+ listeHoraire);
				//System.out.println("regle \n"+listeRegleDate);
                
                
                //1 calcul des dates suivants les règles de calcul et création des entrées dans date_service_reel
                Iterator i=listeRegleDate.iterator();
                while (i.hasNext()){
                    regleDateService crt = (regleDateService)i.next();
                   // System.out.println(crt);
                    if (crt.type.equals("S")) calcDateSurJourSemaine(Integer.parseInt(serviceNum),crt,listeHoraire);
                    
                    
                    
                    
                }
                
				
			}
			
			
		}catch (Exception E) {
			System.out.println(E);
		}
	}

}